//
//  HLSingViewController.m
//  HLMusicBox
//
//  Created by hulinhu on 2017/12/27.
//  Copyright © 2017年 hulinhu. All rights reserved.
//

#import "HLSingViewController.h"
#import "MusicPlayerManager.h"
#import "HLTopSingView.h"
#import "HLMiddleView.h"
#import "HLBottomView.h"
#import "HLSongViewModel.h"
#import "HLSongListView.h"

@interface HLSingViewController ()

@property (nonatomic, strong) HLSongPlayManager *songPlayManager;
@property (nonatomic, strong) MusicPlayerManager *musicPlayer;

@property (nonatomic, strong) HLTopSingView *topView;
@property (nonatomic, strong) HLBottomView *bottomView;

@property (nonatomic, strong) HLSongViewModel *songViewModel;

@property (nonatomic, strong) HLSongListView *songListView;
@property (nonatomic, strong) UIView *shadowView;


@end

@implementation HLSingViewController
-(instancetype)init{
    self = [super init];
    if (self) {
        _musicPlayer = [MusicPlayerManager shareInstance];
        _songPlayManager = [HLSongPlayManager shareInstance];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.hidden = YES;
    // 初始化SubView
    [self configSubView];
    [self playStateRecover];

}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getShuffleAndRepeatState];
}

#pragma mark
#pragma mark - 设置视图

-(void)configSubView {
    
    // 设置背景图片
    [self setBackgroundBlurEffect];

    //添加顶部实体
    [self.view addSubview:self.topView];
    [[self.topView.backBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    // 添加唱片
    [self.view addSubview:self.midView];
    
    // 底部控制
    [self.view addSubview:self.bottomView];
    
    // 滑动事件
    [[self.bottomView.songSlider rac_signalForControlEvents:UIControlEventValueChanged] subscribeNext:^(id x) {
        // 更新播放时间
        [self updateTime];
        //如果当前时暂停状态，则自动播放
        if (_musicPlayer.play.rate == 0) {
            self.bottomView.playPause.image = [UIImage imageNamed:@"cm2_fm_btn_play"];
            [self.midView.playSongImage resumeRotate];
            [_musicPlayer startPlay];
        }
    }];
    
    // 点击事件
    [[self.bottomView.songSlider rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        // 更新播放时间
        [self updateTime];
        //如果当前时暂停状态，则自动播放
        if (_musicPlayer.play.rate == 0) {
            self.bottomView.playPause.image = [UIImage imageNamed:@"cm2_fm_btn_play"];
            [self.midView.playSongImage resumeRotate];
            [_musicPlayer startPlay];
        }
    }];
}
// 数据绑定
-(void)setSongInforModel:(HLSongItemModel *)itemModel {
    
    // 顶部
    self.topView.songName.text = itemModel.songinfo.title;
    self.topView.singerName.text = [NSString stringWithFormat:@"- %@ -",itemModel.songinfo.author];
    // 中间
    [self.midView setModel:itemModel];
}
// 实时播放数据
-(void)setSongPlayCurretTime:(float)currentTime totalTime:(float)totalTime {
    
    // 底部进度
    self.bottomView.currentTime.text = [_songPlayManager intToString:(int)currentTime];
    self.bottomView.totalTime.text = [_songPlayManager intToString:(int)totalTime];
    self.bottomView.songSlider.value = (float) ( currentTime / totalTime );
    
    // 设置歌词
    if (_songPlayManager.mLRCDictinary.count > 1) {
        NSInteger songLrcIndex = _songPlayManager.lrcIndex;
        // 没有在拖拽
        if (!self.midView.lrcView.isDragging) {
            if (songLrcIndex <= _songPlayManager.mLRCDictinary.count-1) {
                // 时间大于数组时间的时候进行 滚动换行
                if ((int)currentTime >= [_songPlayManager stringToInt:_songPlayManager.mTimeArray[songLrcIndex]]) {
                      NSLog(@"songInfo   当前播放时间：%d", [_songPlayManager stringToInt:_songPlayManager.mTimeArray[songLrcIndex]]);
                    self.midView.lrcView.currentRow = songLrcIndex;
                    [self refreshLRCIndex:songLrcIndex];
                    _songPlayManager.lrcIndex = songLrcIndex + 1;
                }else{
                    if (songLrcIndex != 0) { // 非第一行
                        if ((int)currentTime >= [_songPlayManager stringToInt:_songPlayManager.mTimeArray[songLrcIndex-1]] && (int)currentTime < [_songPlayManager stringToInt:_songPlayManager.mTimeArray[songLrcIndex]] ) {
                            self.midView.lrcView.currentRow = songLrcIndex-1;
                            [self refreshLRCIndex:songLrcIndex-1];
                        }
                    }
                }
            }
        }
    }
}


-(void)refreshLRCIndex:(NSInteger)songLrcIndex{
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:songLrcIndex inSection:0];
    
    // 必须放到主线程 要不无欢动效果
     dispatch_async(dispatch_get_main_queue(), ^{
        // 滚动下标
        [self.midView.lrcView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
        // 锁屏设置
        [self.midView.lrcView.lockScreenTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
     });
    [self.midView.lrcView reloadData];
    [self.midView.lrcView.lockScreenTableView reloadData];
}

#pragma mark
#pragma mark - 恢复播放
-(void)playStateRecover {
    [self.midView.playSongImage startRotating];
    
    if (self.musicPlayer.play.rate == 1) {
        NSLog(@" 播放 ")
        self.bottomView.playPause.image = [UIImage imageNamed:@"cm2_fm_btn_play"];
        [self.midView.playSongImage resumeRotate];
    }else {
        NSLog(@"停止")
        self.bottomView.playPause.image = [UIImage imageNamed:@"cm2_fm_btn_pause"];
        [self.midView.playSongImage  stopRotating];
    }
}


#pragma mark
#pragma mark - 处理点击时间
-(void)handleBtnClick:(NSInteger)index{
    NSLog(@" index -- %ld",index);
    
    if (index == MUSIC_PREONE) {
        [self preSongAction];
    }else if (index == MUSIC_NEXTONE){
        [self nextSongAction];
    }else if (index == MUSIC_BEGPAUSE){
        if (_musicPlayer.play.rate == 0) {
            NSLog(@"播放！");
            _bottomView.playPause.image = [UIImage imageNamed:@"cm2_fm_btn_play"];
            [_midView.playSongImage resumeRotate];
            [_musicPlayer startPlay];
        } else {
            NSLog(@"暂停");
            _bottomView.playPause.image = [UIImage imageNamed:@"cm2_fm_btn_pause"];
            [_midView.playSongImage stopRotating];
            [_musicPlayer stopPlay];
        }
    }else if (index == MUSIC_PLAYMODE){
        [self shuffleAndRepeat];
    }else if (index == MUSIC_PLAYLIST){
        [self songListAction];
    }
}
#pragma - mark 播放模式按键action
-(void)getShuffleAndRepeatState{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSNumber *repeatAndShuffleNumber = [defaults objectForKey:@"SHFFLEANDREPEATSTATE"];
    if (repeatAndShuffleNumber == nil) {
        _musicPlayer.shuffleAndRepeatState = RepeatPlayMode;
     }
    else{
        _musicPlayer.shuffleAndRepeatState = (ShuffleAndRepeatState)[repeatAndShuffleNumber integerValue];
    }
    
    switch (_musicPlayer.shuffleAndRepeatState) {
        case RepeatPlayMode:{
            _bottomView.playMode.image = [UIImage imageNamed:@"cm2_icn_loop"];
        }
            break;
        case RepeatOnlyOnePlayMode: {
            _bottomView.playMode.image = [UIImage imageNamed:@"cm2_icn_one"];
        }
            break;
        case ShufflePlayMode: {
            _bottomView.playMode.image = [UIImage imageNamed:@"cm2_icn_shuffle"];
            break;
        default:
            break;
        }
    }
}
-(void)shuffleAndRepeat {
    switch (_musicPlayer.shuffleAndRepeatState) {
        case RepeatPlayMode: {
            _bottomView.playMode.image = [UIImage imageNamed:@"cm2_icn_one"];
            _musicPlayer.shuffleAndRepeatState = RepeatOnlyOnePlayMode;  //单曲循环
            [self showMiddleHint:@"单曲循环"];
          }
            break;
        case RepeatOnlyOnePlayMode: {
            _bottomView.playMode.image = [UIImage imageNamed:@"cm2_icn_shuffle"];
            _musicPlayer.shuffleAndRepeatState = ShufflePlayMode;
            [self showMiddleHint:@"列表播放"];
        }
            break;
        case ShufflePlayMode: {
            _bottomView.playMode.image = [UIImage imageNamed:@"cm2_icn_loop"];
            _musicPlayer.shuffleAndRepeatState = RepeatPlayMode;
            [self showMiddleHint:@"随机播放"];
        }
            break;
        default:
            break;
    }
    
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:_musicPlayer.shuffleAndRepeatState] forKey:@"SHFFLEANDREPEATSTATE"];//存储路径
}

#pragma mark
#pragma mark - 歌曲列表
-(void)songListAction{
    
    // 空背景加手势
    self.shadowView = [GFControl createUIViewWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight) bgColor:[[UIColor blackColor] colorWithAlphaComponent:0.0] cornerRadius:0 tapAction:^{
        // 设置播放模式
        [self getShuffleAndRepeatState];
        
        // SongListView隐藏动画
        [UIView animateWithDuration:0.3 animations:^{
            self.songListView.transform = CGAffineTransformMakeTranslation(0.0, KScreenHeight);
            self.shadowView.alpha = 0;
        } completion:^(BOOL finished) {
            [self.shadowView removeFromSuperview];
            [self.songListView removeFromSuperview];
        }];
    }];
    
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    [window addSubview:self.shadowView];
    [window addSubview:self.songListView];
    // 获取播放模式
    [self.songListView getShuffleAndRepeatState];
    
    self.songListView.transform = CGAffineTransformMakeTranslation(0.0, KScreenHeight);
    self.shadowView.transform = CGAffineTransformMakeTranslation(0.0, KScreenHeight);
    [UIView animateWithDuration:0.3 animations:^{
        self.shadowView.transform = CGAffineTransformMakeTranslation(0.0, 0.0);
        self.songListView.transform = CGAffineTransformMakeTranslation(0.0, KScreenHeight * (1.0 - 0.618));
    } completion:^(BOOL finished){
        self.shadowView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
    }];
    
}

#pragma - mark 上一曲
-(void)preSongAction {
    
    _musicPlayer.playingIndex = self.songPlayManager.playSongIndex;
    
    switch (_musicPlayer.shuffleAndRepeatState) {
        case RepeatPlayMode: {
            if (_musicPlayer.playingIndex == 0){ //第一首
                _musicPlayer.playingIndex = self.songPlayManager.songListArray.count - 1;  //跳到最后一首
            }
            else {
                _musicPlayer.playingIndex--;    //索引为上一首
            }
        }
            break;
        case RepeatOnlyOnePlayMode: {
            
        }
            break;
        case ShufflePlayMode: {
            if (_musicPlayer.playingIndex == 0){ //是第一首歌
                _musicPlayer.playingIndex = [self getRandomNumber:1 with:(self.songPlayManager.songListArray.count - 1)];//播放除第一首歌之外的所有歌曲
            }
            else{
                _musicPlayer.playingIndex = [self getRandomNumber:0 with:(_musicPlayer.playingIndex - 1)];
            }
        }
            break;
        default:
            break;
    }
    if (_musicPlayer.playingIndex != self.songPlayManager.playSongIndex) {
        if (self.songPlayManager.playSongIndex > 0) {
            HLSongListModel *info = self.songPlayManager.songListArray[_musicPlayer.playingIndex];
            NSLog(@"即将播放下一首歌曲: 《%@》 --- %@", info.title,info.song_id);
            [self.songPlayManager requestCurrentPlaySong:info.song_id playSongIndex:_musicPlayer.playingIndex];
        }
    } else {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"repeatPlay" object:self];
    }
    
}
-(void)nextSongAction {
    
    _musicPlayer.playingIndex = self.songPlayManager.playSongIndex;
    
    switch (_musicPlayer.shuffleAndRepeatState) {
            
        case RepeatPlayMode: {
            _musicPlayer.playingIndex++;
            if (_musicPlayer.playingIndex >= self.songPlayManager.songListArray.count) {   //最后一首
                _musicPlayer.playingIndex = 0;              //跳到第一首
            }
        }
            break;
        case RepeatOnlyOnePlayMode:{
            
        }
            break;
        case ShufflePlayMode: {
            if (_musicPlayer.playingIndex == self.songPlayManager.songListArray.count - 1){ //最后一首
                _musicPlayer.playingIndex = [self getRandomNumber:0 with:(self.songPlayManager.songListArray.count - 2)];//重头开始不包括本首歌
            }
            else {
                _musicPlayer.playingIndex = [self getRandomNumber:(_musicPlayer.playingIndex + 1) with:(self.songPlayManager.songListArray.count - 1)];//不包括本首歌
            }
        }
            break;
        default:
            break;
    }
    
    if (_musicPlayer.playingIndex != self.songPlayManager.playSongIndex ) {
        if (self.songPlayManager.playSongIndex < self.songPlayManager.songListArray.count) {
            HLSongListModel *info = self.songPlayManager.songListArray[_musicPlayer.playingIndex];
            NSLog(@"即将播放下一首歌曲: 《%@》 --- %@", info.title,info.song_id);
               [self.songPlayManager requestCurrentPlaySong:info.song_id playSongIndex:_musicPlayer.playingIndex];
        }
    } else {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"repeatPlay" object:self];
    }
}

#pragma mark
#pragma mark - lazy load

-(HLTopSingView *)topView {
    if (!_topView) {
        _topView = [[[NSBundle mainBundle] loadNibNamed:@"HLTopSingView" owner:nil options:nil] lastObject];
        _topView.frame = CGRectMake(0, 0, KScreenWidth, KScreenHeight/6.0);
        _topView.backgroundColor = [UIColor clearColor];
    }
    return _topView;
}
-(HLMiddleView *)midView{
    if (!_midView) {
        _midView = [[HLMiddleView alloc] initWithFrame:CGRectMake(0, _topView.bottom, KScreenWidth, KScreenHeight/6.0 * 4)];
        _midView.backgroundColor = [UIColor clearColor];

    }
    return _midView;
}
-(HLBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[HLBottomView alloc] initWithFrame:CGRectMake(0, _midView.bottom, KScreenWidth, KScreenHeight/6.0 ) playbtnClick:^(NSInteger index) {
            [self handleBtnClick:index];
        }];
        _bottomView.backgroundColor = [UIColor clearColor];
    }
    return _bottomView;
    
}
-(HLSongViewModel *)songViewModel {
    
    if (!_songViewModel) {
        _songViewModel = [[HLSongViewModel alloc] init];
    }
    return _songViewModel;
    
}
-(HLSongListView *)songListView {
    if (!_songListView) {
        _songListView = [[HLSongListView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight*0.618) topbtnClick:^(NSInteger index) {
            [self handleBtnClick:index];
        }];
    }
    return _songListView;
}


#pragma - mark 获取随机数，用于随机播放
-(NSUInteger) getRandomNumber:(NSUInteger)from with:(NSUInteger)to//包括两边边界
{
    NSUInteger res =  from + (arc4random() % (to - from + 1));
    return res;
}

#pragma mark - 播放模式提示框
- (void)showMiddleHint:(NSString *)hint {
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.userInteractionEnabled = NO;
    hud.mode = MBProgressHUDModeText;
    hud.label.font = [UIFont systemFontOfSize:15];
    hud.label.text = hint;
    hud.margin = 10.f;
    hud.offset = CGPointMake(0.f, 0.f);
    hud.removeFromSuperViewOnHide = YES;
    [hud hideAnimated:YES afterDelay:2.f];
}

#pragma mark
#pragma mark - 设置模糊
-(void)setBackgroundBlurEffect {
    
    // 设置背景图
    CGRect frame = CGRectMake(-KScreenWidth/ 2, -KScreenHeight / 2, KScreenWidth * 2, KScreenHeight * 2);
    UIImageView *backgroundImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"backgroundImage3"]];
    backgroundImage.frame = frame;
    [self.view addSubview:backgroundImage];
    
    // 毛玻璃效果
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *visualView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    visualView.alpha = 1.0;
    visualView.frame = frame;
    visualView.clipsToBounds = true;
    [backgroundImage addSubview:visualView];
}
#pragma mark - 更新播放时间
-(void) updateTime {
    
    CMTime duration = _musicPlayer.play.currentItem.asset.duration;
    
    // 歌曲总时间和当前时间
    Float64 completeTime = CMTimeGetSeconds(duration);
    Float64 currentTime = (Float64)(self.bottomView.songSlider.value) * completeTime;
    
    //播放器定位到对应的位置
    CMTime targetTime = CMTimeMake((int64_t)(currentTime), 1);
    [_musicPlayer.play seekToTime:targetTime];
    
    // 定位歌词位置
    int index = 0;
    for (NSString *indexStr in _songPlayManager.mTimeArray) {
        if ((int)currentTime < [_songPlayManager stringToInt:indexStr]) {
            _songPlayManager.lrcIndex = index;
        } else {
            index = index + 1;
        }
    }
}

@end
